<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\property\users;

use think\App;
use app\controller\property\Base;
use app\common\repositories\users\UsersRepository;
use app\validate\property\users\PropertyUsersValidate;
use app\common\repositories\property\group\PropertyGroupRepository;
use app\common\repositories\property\users\PropertyUsersRepository;
use app\common\repositories\property\auth\PropertyAuthRoleRepository;

class PorpertyUsers extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyUsersRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    protected function commonParams()
    {
        $this->assign([
            'addGroupAuth' => property_auth('propertyGroupAdd'),
            'addRoleAuth' => property_auth('propertyAuthRoleAdd'),
        ]);
    }

    /**
     * 用户操作日志
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-16 22:20
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'group_id' => '',
                'rule_id' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        } else {
            return $this->fetch('property/users/list', [
                'addAuth' => property_auth('propertyUsersAdd'),
                'editAuth' => property_auth('propertyUsersEdit'),
                'delAuth' => property_auth('propertyUsersDel'),
                'detailAuth' => property_auth('propertyUsersDetail')
            ]);
        }
    }

    /**
     * 添加管理员
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-18 17:29
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->get('get_type') == 'getRoleList') {
            /** @var propertyAuthRoleRepository $roleRepository */
            $roleRepository = app()->make(propertyAuthRoleRepository::class);
            $roleList = $roleRepository->getSearch(['property_id' => $this->request->propertyId])->field('id,name')->select();
            return json()->data(['code' => 0, 'data' => $roleList]);
        } elseif ($this->request->isAjax() && $this->request->get('get_type') == 'getGroupData') {
            /** @var PropertyGroupRepository $groupRepository */
            $groupRepository = app()->make(PropertyGroupRepository::class);
            $groupData = $groupRepository->getCascaderData(['is_show' => 1]);
            return json()->data(['code' => 0, 'data' => $groupData]);
        } elseif ($this->request->isPost()) {
            $param = $this->request->param([
                'number' => '',
                'account' => '',
                'email' => '',
                'mobile' => '',
                'username' => '',
                'password' => '',
                'remark' => '',
                'group_id' => '',
                'role_ids' => [],
                'avatar_url' => '',
                'guard_card' => '',
                'guard_password' => '',
            ]);
            $param['is_show'] = 1;
            validate(propertyUsersValidate::class)->scene('add')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'number', $param['number'])) {
                return $this->error($param['number'] . ' 已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加管理员失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('property/users/add');
        }
    }

    /**
     * 编辑管理员
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isAjax() && $this->request->get('get_type') == 'getGroupData') {
            /** @var propertyGroupRepository $groupRepository */
            $groupRepository = app()->make(propertyGroupRepository::class);
            $groupData = $groupRepository->getCascaderData(['is_show' => 1]);
            return json()->data(['code' => 0, 'data' => $groupData]);
        } elseif ($this->request->isPost()) {
            $param = $this->request->param([
                'number' => '',
                'account' => '',
                'email' => '',
                'mobile' => '',
                'username' => '',
                'password' => '',
                'is_show' => '',
                'remark' => '',
                'group_id' => '',
                'role_ids' => [],
                'avatar_url' => '',
                'guard_card' => '',
                'guard_password' => '',
            ]);
            validate(propertyUsersValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->propertyUId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑管理失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('property/users/edit', [
                'info' => $info,
            ]);

        }
    }

    /**
     * 修改登录密码
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-14 08:47
     */
    public function editPassword(UsersRepository $repository)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'old_password' => '',
                'password' => '',
                're_password' => ''
            ]);
            validate(propertyUsersValidate::class)->scene('editPassword')->check($param);
            $userInfo = $repository->get($this->request->userId);
            if (!$repository->passwordVerify($param['old_password'], $userInfo['password'])) {
                return $this->error('原密码错误');
            }
            try {
                $res = $repository->update($userInfo['id'], [
                    'password' => $param['password']
                ]);
                if ($res) {
                    $this->repository->clearSessionInfo();
                    return $this->success('修改成功，请重新登录');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改密码失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('property/users/edit_password');
        }
    }

    /**
     * 修改自己的信息
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-14 08:49
     */
    public function editInfo(UsersRepository $repository)
    {
        $userInfo = $repository->get($this->request->userId);
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'username' => '',
                'email' => '',
                'mobile' => ''
            ]);
            validate(propertyUsersValidate::class)->scene('selfEdit')->check($param);
            try {
                $res = $repository->editInfo($userInfo, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改资料失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('property/users/edit_info', [
                'userInfo' => $userInfo
            ]);
        }
    }


    /**
     * 删除管理员
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->propertyUId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除管理员失败', $e);
            return $this->error('网络错误');
        }
    }


    public function detail()
    {
        $id = (int)$this->request->param('id');
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('property/users/detail', [
            'info' => $info,
            'addUserRoleAuth' => property_auth('propertyUsersRoleAdd'),
            'editUserRoleAuth' => property_auth('propertyUsersRoleEdit'),
            'delUserRoleAuth' => property_auth('propertyUsersRoleDel'),
        ]);
    }


}